package net.uzen.office.common.util;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DocumentUtil {

	private static final Log logger = LogFactory.getLog(DocumentUtil.class);

	public static void parseXML(InputStream is) {

		try {

			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			documentBuilderFactory.setIgnoringComments(true);
			documentBuilderFactory.setIgnoringElementContentWhitespace(true);

			DocumentBuilder documentBuilder = documentBuilderFactory
					.newDocumentBuilder();
			Document document = documentBuilder.parse(is);

			Element element = document.getDocumentElement();

			NodeList nodeList = element.getChildNodes();

			logger.debug(" >> nodeList.length : " + nodeList.getLength());

			for (int index = 0; index < nodeList.getLength(); index++) {

				Node node = nodeList.item(index);

				logger.debug(" >> Node[" + index + "] : {" + node.getNodeName()
						+ " : " + node.getTextContent() + "}");
			}

		} catch (Exception e) {

		}
	}

	public static String getXMLNodeValue(InputStream is, String nodeName) {

		String nodeValue = null;

		try {

			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			documentBuilderFactory.setIgnoringComments(true);
			documentBuilderFactory.setIgnoringElementContentWhitespace(true);

			DocumentBuilder documentBuilder = documentBuilderFactory
					.newDocumentBuilder();
			Document document = documentBuilder.parse(is);

			Element element = document.getDocumentElement();

			NodeList nodeList = element.getChildNodes();

			logger.debug(" >> nodeList.length : " + nodeList.getLength());

			for (int index = 0; index < nodeList.getLength(); index++) {

				Node node = nodeList.item(index);

				logger.debug(" >> Node[" + index + "] : {" + node.getNodeName()
						+ " : " + node.getTextContent() + "}");

				if (nodeName.equals(node.getNodeName())) {

					nodeValue = node.getTextContent();
					break;

				}
			}

		} catch (Exception e) {

		}

		logger.debug(">> [!] : " + nodeName + "|" + nodeValue);

		return nodeValue;
	}
}
